package com.briup.cloud.framework.resource.web.rest;

import com.briup.framework.utils.web.Response;
import com.briup.framework.utils.web.SecurityUserDetails;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import feign.FeignException;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import java.security.Principal;
import java.util.Map;

/**
 * @Author guomiao
 * @Date 2022/3/22 15:26
 */
@Slf4j
@Component
public class RemoteServiceFallbackFactory implements FallbackFactory<RemoteService> {
    public RemoteServiceFallbackFactory(){
        log.info("服务回滚。。。。。。。。。。");
    }
    @Autowired
    ObjectMapper mapper;

    @Override
    public RemoteService create(Throwable throwable) {
        System.out.println("RemoteServiceFallBack.....................");
        return new RemoteService() {
            @Override
            public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, Map<String, String> parameters) {
                System.out.println("============.throwalbe: "+throwable);
                if(throwable instanceof FeignException){
                    FeignException ex = (FeignException)throwable;
                    throw new RuntimeException(ex.contentUTF8());
                }else if(throwable instanceof HystrixTimeoutException){
                    throw new RuntimeException("服务正忙，请稍后！");
                }else {
                    HttpHeaders map = new HttpHeaders();
                    ResponseEntity<OAuth2AccessToken> resp = new ResponseEntity<>(map, HttpStatus.BAD_REQUEST);
                    map.add("msg","服务器正忙，请稍后！");
                    return resp;
                }
            }

            @Override
            public Response<SecurityUserDetails> hello() {
                System.out.println("***********************.throwalbe: "+throwable);
                return null;
            }
        };
    }
}
